package com.shycloud.mido.homework.sharding;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Xiaoxing Yu
 * @date 2020/11/19 下午1:56
 **/
@Slf4j
@Configuration
public class WorkIdConfig {

	/**
	 * 设置workerIdValue的值
	 */
	static {

		int workId = 0;
		try {
			workId = getWorkId();
		} catch (Exception e) {
			log.error("生成workId发生异常.", e);
		}

		System.setProperty("workerIdValue", String.valueOf(workId));
	}


	/**
	 * 根据机器名称生成workId
	 * @return
	 */
	private static int getWorkId() {
		String hostAddress = System.getenv("HOSTNAME");
		log.info("============= hostAddress: {} =============", hostAddress);
		int[] ints = StringUtils.toCodePoints(hostAddress);
		int sum = 0;

		for (int b : ints) {
			sum += b;
		}

		int workId = (sum % 32);
		log.info("============== workId：{} =============", workId);
		return workId;
	}


}
